﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utilities.Web.ExtJs
{
    /// <summary>
    /// Adapts the tree node information returned by the server to the one ExtJs can understand
    /// </summary>
    public class TreeEnvelope : Envelope
    {
        public static TreeEnvelope Process(Func<IList<TreeNodeData>> function)
        {
            TreeEnvelope envelope = new TreeEnvelope();

            try
            {
                envelope.children = new List<TreeNode>();

                foreach (TreeNodeData node in function())
                {
                    envelope.children.Add(new TreeNode
                    {
                        id = node.Id.ToString(),
                        text = node.Text,
                        leaf = node.IsLeaf
                    });
                }
            }
            catch (Exception exception)
            {
                envelope.SetError(exception);
            }

            return envelope;
        }

        public List<TreeNode> children { get; set; }

        public class TreeNode
        {
            /// <summary>
            /// The id of the node. It is a combination of the node type enumeration and the id of the enumeration
            /// </summary>
            public string id { get; set; }

            /// <summary>
            /// The text of the node
            /// </summary>
            public string text { get; set; }

            /// <summary>
            /// Whether the node is expanded
            /// </summary>
            public bool expanded { get; set; }

            /// <summary>
            /// Whether the node is a leaf
            /// </summary>
            public bool leaf { get; set; }

            /// <summary>
            /// The class to show the image icon
            /// </summary>
            public string iconCls { get; set; }
        }
    }
}
